﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using MiPeiPei.Utility.Pay.WeChat;

namespace NetPay.WeChat.ProfitSharing
{
    /// <summary>
    /// 商户平台证书
    /// </summary>
	public class Certificates
	{
        /// <summary>
        /// 获取商户平台证书序列号
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetSerialNo()
        {
            var serial_no = "";

            var url = "https://api.mch.weixin.qq.com/v3/certificates";
            HttpClient client = new HttpClient(new HttpClientHelper(Config.MCHID, Config.SERIAL_NO));
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(new System.Net.Http.Headers.ProductHeaderValue("wechatpayv3demo", "1.1.0")));
            var result = await client.GetAsync(url);
            string data = await result.Content.ReadAsStringAsync();
            if (!string.IsNullOrEmpty(data))
            {
                JObject obj = (JObject)JsonConvert.DeserializeObject(data);

                // 如果有多个证书，需要添加条件自行处理一下
                foreach (var item in obj["data"])
                {
                    serial_no = (string?)item["serial_no"];
                }
            }

            return serial_no;
        }

        /// <summary>
        /// 获取商户平台证书公钥
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetCertificate()
        {
            var public_key = "";

            var url = "https://api.mch.weixin.qq.com/v3/certificates";
            HttpClient client = new HttpClient(new HttpClientHelper(Config.MCHID, Config.SERIAL_NO));
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(new System.Net.Http.Headers.ProductHeaderValue("wechatpayv3demo", "1.1.0")));
            var result = await client.GetAsync(url); 
            string data = await result.Content.ReadAsStringAsync();
            JObject obj = (JObject)JsonConvert.DeserializeObject(data);

            foreach (var item in obj["data"])
            {
                // var effective_time = item["effective_time"].ToString();
                // var algorithm = item["encrypt_certificate"]["algorithm"].ToString();
                var associated_data = item["encrypt_certificate"]["associated_data"].ToString();
                var ciphertext = item["encrypt_certificate"]["ciphertext"].ToString();
                var nonce = item["encrypt_certificate"]["nonce"].ToString();
                // var expire_time = item["expire_time"].ToString();
                // var serial_no = item["serial_no"].ToString();

                // 如果有多个证书，需要添加条件自行处理一下
                public_key = AesGcmHelper.AesGcmDecrypt(associated_data, nonce, ciphertext);

                // 以下为验签省略，暂时用不到
                // X509Certificate2 x509Cert = new X509Certificate2(Encoding.UTF8.GetBytes(decrypt_data));
            }

            return public_key;
        }
    }
}

